using System;
using System.Collections.Generic;
using Mall.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Mall.Api.ParamModel;
using Newtonsoft.Json;
using Mall.Api.Repository;
using Mall.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Mall.Api.Filters;

namespace Mall.Api.Controllers
{
    /// <summary>
    /// 供应商管理
    /// </summary>


    // [Authorize]

    [ApiController]
    [Route("supplier")]
    public class SupplierController : ControllerBase
    {
        private IRepository<Supplier> _supplier;
        private IRepository<Brand> _brand;

        private readonly IConfiguration _configuration;

        public SupplierController(IConfiguration configuration, IRepository<Supplier> supplier, IRepository<Brand> brand)
        {
            _configuration = configuration;
            _supplier = supplier;
            _brand = brand;
        }

        /// <summary>
        /// 获取供应商列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;

            // 获得所有满足条件的记录
            var supplier = from suppliers in _supplier.Table
                           join brand in _brand.Table on suppliers.BrandId equals brand.Id
                           // orderby suppliers.Id descending
                           where suppliers.IsDeleted == false
                           select new
                           {
                               Id = suppliers.Id,
                               AccountName = suppliers.AccountName,
                               AccountPassword = suppliers.AccountPassword,
                               SupplierName = suppliers.SupplierName,
                               Owner = suppliers.Owner,
                               ManagementTypes = suppliers.ManagementTypes,
                               BrandName = brand.BrandName,
                               Address = suppliers.Address,
                               Phone = suppliers.Phone,
                               StoreName = suppliers.StoreName,
                               Priority = suppliers.Priority,
                               CreatedTime = suppliers.CreatedTime


                           };



            if (!string.IsNullOrEmpty(pager.KeyWord))
            {
                supplier = supplier.Where(u => u.SupplierName.Contains(pager.KeyWord) || u.StoreName.Contains(pager.KeyWord) || u.AccountName.Contains(pager.KeyWord)|| u.Owner.Contains(pager.KeyWord));
            }

            // 对获得的记录分页
            var u = supplier.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = supplier.Count() } },
                Msg = "获取供应商列表成功^_^"
            };
            return res;
        }






        /// <summary>
        /// 修改供应商信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public dynamic Put(int id, NewSupplier model)
        {
            var supplier = _supplier.GetById(id);
            var b = supplier.BrandId;
            var brans = _brand.GetById(b);

            if (supplier != null)
            {
                supplier.AccountName = model.AccountName;
                supplier.AccountPassword = model.AccountPassword;
                supplier.SupplierName = model.SupplierName;
                supplier.Introduction = model.Introduction;
                supplier.ManagementTypes = model.ManagementTypes;
                supplier.Owner = model.Owner;
                supplier.Address = model.Address;
                supplier.Phone = model.Phone;
                supplier.StoreName = model.StoreName;
                supplier.Priority = model.Priority;
                supplier.IsDeleted = model.IsDeleted;
                supplier.IsActived = model.IsActived;
                brans.BrandName = model.BrandName;



                supplier.UpdatedTime = DateTime.Now;
                _supplier.Update(supplier);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = supplier,
                    Msg = string.Format("你修改或删除的供应商的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的供应商不存在，请确认后重试"
                });
            }
        }







        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Post(NewSupplier model)
        {

            var accountName = model.AccountName.Trim();
            var accountPassword = model.AccountPassword.Trim();
            var supplierName = model.SupplierName.Trim();
            var introduction = model.Introduction.Trim();
            var managementTypes = model.ManagementTypes.Trim();
            var owner = model.Owner.Trim();
            var address = model.Address.Trim();
            var phone = model.Phone.Trim();
            var storeName = model.StoreName.Trim();
            var priority = model.Priority;

            var brandName = model.BrandName;
            // var brandId = _brand.Table.Where(b => b.BrandName == brandName).FirstOrDefault().Id;
            var s = _supplier.Table.Where(s => s.AccountName == accountName).FirstOrDefault();
            if (s != null)
            {

                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "供应商已存在"
                };
                return JsonHelper.Serialize(tmp);
            }

            if (string.IsNullOrEmpty(accountName))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "供应商账号不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }
            var brand = new Brand
            {
                BrandName = brandName

            };

            _brand.Insert(brand);

            var supplier = new Supplier
            {
                AccountName = accountName,
                AccountPassword = accountPassword,
                SupplierName = supplierName,
                Introduction = introduction,
                ManagementTypes = managementTypes,
                Owner = owner,
                Brand = _brand.Table.Single(b => b.Id == brand.Id),
                Address = address,
                Phone = phone,
                StoreName = storeName,
                Priority = priority,
                RolesId = 4


            };

            _supplier.Insert(supplier);


            var res = new
            {
                Code = 200,
                Data = new
                {
                    Supplier = supplier

                },
                Msg = "添加供应商成功"
            };
            return JsonHelper.Serialize(res);
        }







        /// <summary>
        /// 根据指定id查找数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var supplier = _supplier.GetById(id);

            if (supplier == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定供应商不存在"
                };

            }
            return new
            {
                Code = 200,
                Data = supplier,
                Msg = "获取供应商成功^_^"
            };

        }






        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var supplier = _supplier.GetById(id);
            if (supplier != null)
            {
                _supplier.Delete(id);
                return new
                {
                    Code = 200,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }

        }




    }

}